import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { walletApi } from '../../services/apiService';

const CredentialManager = () => {
  const [credentials, setCredentials] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [filter, setFilter] = useState('all'); // all, active, expired, revoked
  const navigate = useNavigate();

  useEffect(() => {
    const fetchCredentials = async () => {
      try {
        setLoading(true);
        const response = await walletApi.listCredentials();
        if (response.success) {
          setCredentials(response.credentials);
        } else {
          setError('获取凭证列表失败');
        }
      } catch (error) {
        console.error('获取凭证列表出错:', error);
        setError('获取凭证列表时发生错误，请稍后再试');
      } finally {
        setLoading(false);
      }
    };

    fetchCredentials();
  }, []);

  // 计算凭证状态
  const getCredentialStatus = (credential) => {
    const now = new Date();
    if (credential.revoked) {
      return 'revoked';
    } else if (credential.expirationDate && new Date(credential.expirationDate) < now) {
      return 'expired';
    } else {
      return 'active';
    }
  };

  // 过滤凭证
  const filteredCredentials = credentials.filter(credential => {
    if (filter === 'all') return true;
    return getCredentialStatus(credential) === filter;
  });

  // 删除凭证
  const handleDeleteCredential = async (id) => {
    if (window.confirm('确定要删除此凭证吗？此操作不可撤销。')) {
      try {
        const response = await walletApi.deleteCredential(id);
        if (response.success) {
          setCredentials(credentials.filter(cred => cred.id !== id));
        } else {
          alert('删除凭证失败: ' + (response.error || '未知错误'));
        }
      } catch (error) {
        console.error('删除凭证出错:', error);
        alert('删除凭证时发生错误，请稍后再试');
      }
    }
  };

  if (loading) {
    return (
      <div className="loading-spinner">
        <div className="spinner-border text-primary" role="status">
          <span className="visually-hidden">加载中...</span>
        </div>
      </div>
    );
  }

  return (
    <div className="credential-manager">
      <div className="d-flex justify-content-between align-items-center mb-4">
        <h4 className="section-title">凭证管理</h4>
        <button
          className="btn btn-primary"
          onClick={() => navigate('/wallet/credentials/import')}
        >
          <i className="bi bi-download me-2"></i>
          导入凭证
        </button>
      </div>

      {error && <div className="alert alert-danger">{error}</div>}

      {/* 筛选器 */}
      <div className="card mb-4">
        <div className="card-body">
          <div className="btn-group w-100">
            <button
              className={`btn ${filter === 'all' ? 'btn-primary' : 'btn-outline-primary'}`}
              onClick={() => setFilter('all')}
            >
              全部凭证
            </button>
            <button
              className={`btn ${filter === 'active' ? 'btn-primary' : 'btn-outline-primary'}`}
              onClick={() => setFilter('active')}
            >
              <i className="bi bi-check-circle me-1"></i> 有效
            </button>
            <button
              className={`btn ${filter === 'expired' ? 'btn-primary' : 'btn-outline-primary'}`}
              onClick={() => setFilter('expired')}
            >
              <i className="bi bi-clock-history me-1"></i> 过期
            </button>
            <button
              className={`btn ${filter === 'revoked' ? 'btn-primary' : 'btn-outline-primary'}`}
              onClick={() => setFilter('revoked')}
            >
              <i className="bi bi-x-circle me-1"></i> 撤销
            </button>
          </div>
        </div>
      </div>

      {filteredCredentials.length === 0 ? (
        <div className="alert alert-info">
          {filter === 'all' ? (
            '您还没有任何凭证。点击"导入凭证"按钮开始添加。'
          ) : (
            `没有${filter === 'active' ? '有效' : filter === 'expired' ? '过期' : '被撤销'}的凭证。`
          )}
        </div>
      ) : (
        <div className="row g-4">
          {filteredCredentials.map((credential, index) => {
            const status = getCredentialStatus(credential);
            return (
              <div className="col-md-6" key={index}>
                <div className={`card credential-card ${status}`}>
                  <div className="card-body">
                    <div className="d-flex justify-content-between align-items-start mb-3">
                      <h5 className="card-title">
                        {credential.type 
                          ? (Array.isArray(credential.type) 
                              ? (credential.type.length > 1 
                          ? credential.type[credential.type.length - 1]
                                  : credential.type[0])
                              : (typeof credential.type === 'string' 
                                  ? credential.type 
                                  : JSON.stringify(credential.type)))
                          : '未知类型'}
                      </h5>
                      <span className={`status-badge ${status}`}>
                        {status === 'active' 
                          ? '有效' 
                          : status === 'expired' 
                            ? '已过期' 
                            : '已撤销'}
                      </span>
                    </div>
                    
                    <div className="mb-3">
                      <small className="text-muted">发行方:</small>
                      <p className="mb-0 text-truncate" title={credential.issuer}>
                        {credential.issuer}
                      </p>
                    </div>
                    
                    <div className="row mb-3">
                      <div className="col-6">
                        <small className="text-muted">发行日期:</small>
                        <p className="mb-0">
                          {new Date(credential.issuanceDate).toLocaleDateString()}
                        </p>
                      </div>
                      <div className="col-6">
                        <small className="text-muted">过期日期:</small>
                        <p className="mb-0">
                          {credential.expirationDate 
                            ? new Date(credential.expirationDate).toLocaleDateString() 
                            : '永不过期'}
                        </p>
                      </div>
                    </div>
                    
                    <div className="d-flex justify-content-between">
                      <button
                        className="btn btn-primary btn-sm"
                        onClick={() => navigate(`/wallet/credentials/${credential.id}`)}
                      >
                        <i className="bi bi-eye me-1"></i> 查看详情
                      </button>
                      <div className="btn-group btn-group-sm">
                        <button
                          className="btn btn-outline-primary"
                          onClick={() => navigate(`/wallet/proofs?credentialId=${credential.id}`)}
                        >
                          <i className="bi bi-shield-check me-1"></i> 生成证明
                        </button>
                        <button
                          className="btn btn-outline-danger"
                          onClick={() => handleDeleteCredential(credential.id)}
                        >
                          <i className="bi bi-trash"></i>
                        </button>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
};

export default CredentialManager; 